/**
 * 
 */
package org.xelnaga.defiler.web.controller.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.xelnaga.defiler.domain.AddressModel;
import org.xelnaga.defiler.domain.UserModel;
import org.xelnaga.defiler.security.SpringSecurityContext;
import org.xelnaga.defiler.service.AddressService;
import org.xelnaga.defiler.service.UserService;

/**
 * @author qijb
 *
 */
@Controller
@RequestMapping("/domain/address")
public class AddressController {
	@Autowired
	private UserService userSerivce;
    @Autowired
    private AddressService addressService;

	/**
	 * 
	 */
	public AddressController() {
		// TODO Auto-generated constructor stub
	}
	
	protected void referenceData(AddressForm address, Model model) {
		this.list(address, model);
	}
	
    /**
     * Create an FieldForm instance and in the case where an id is present, populate it
     * with raw data coming from the database. The form is accessible from the view
     * as the attribute "fieldForm".
     * 
     * Note: Since this method is annotated with @ModelAttribute, it will be executed
     * before the chosen @RequestMapping annotated handler method. In particular, when 
     * the update method handler is invoked, the form is first populated by
     * this method and then its content is overridden by the data posted by the end-user.
     */
    @ModelAttribute
    protected AddressForm populateForm(@ModelAttribute AddressForm addressForm) {
    	//Populate form data.
    	AddressModel addressModel = addressService.get(addressForm.getAddress());
    	if(null != addressModel) {
    		addressForm.setAddress(addressModel);
    	}
    	return addressForm;
    }
    
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(@ModelAttribute AddressForm addressForm, 
    		BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
        	referenceData(addressForm, model);
            return "domain/address/index";
        }
        addressForm.getAddress().initDefaultValues();
        
        UserModel user = userSerivce.getByLoginName(SpringSecurityContext.getAuthencatedUsername());
		addressForm.getAddress().setUser(user);
        addressService.save(addressForm.getAddress());
        return "redirect:/domain/address";
    }
    //----------------------
    // Update
    //----------------------

    @RequestMapping(value = "update/{pk}", method = RequestMethod.GET)
    public String updateForm(@PathVariable("pk") AddressModel address, Model model) {
    	address = this.addressService.getByPrimaryKey(address.getInode());
    	model.addAttribute("address", address);
    	AddressForm form = new AddressForm();
    	form.getAddress().setUser(address.getUser());
    	this.referenceData(form, model);
        return "domain/address/index";
    }

    @RequestMapping(value = "/update", method = { RequestMethod.PUT, RequestMethod.POST })
    public String update(@ModelAttribute AddressForm addressForm, 
    		BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
        	referenceData(addressForm, model);
            return "domain/address/index";
        }

        addressService.save(addressForm.getAddress());
        return "redirect:/domain/address";
    }

    //----------------------
    // Delete
    //----------------------
    @RequestMapping(value = "/delete/{pk}", method = RequestMethod.GET)
    public String delete(@PathVariable("pk") AddressModel address, Model model) {
    	address = this.addressService.getByPrimaryKey(address.getInode());
    	this.addressService.delete(address);
        return "redirect:/domain/address";
    }

    //----------------------
    // Delete
    //----------------------
    @RequestMapping(value = "/default/{pk}", method = RequestMethod.GET)
    public String setDefault(@PathVariable("pk") AddressModel address, Model model) {
    	address = this.addressService.get(address);
    	String loginName = SpringSecurityContext.getUsername();
    	UserModel user = userSerivce.getByLoginName(loginName);
    	this.userSerivce.saveDefaultAddress(user, address);
        return "redirect:/domain/address";
    }
    
    @RequestMapping( { "/list", "/", "" })
    public String list(@ModelAttribute AddressForm addressForm, Model model) {
    	String loginName = SpringSecurityContext.getUsername();
    	AddressModel address = addressForm.getAddress();
		address.setUser(userSerivce.getByLoginName(loginName));
    	int total = addressService.findCount(address);
        model.addAttribute("addressesCount", total);
        if(total > 0) {
        	model.addAttribute("addresses", addressService.find(address));
        }
        return "domain/address/index";
    }

    /**
     * Catch all binds display search by example form, search by pattern form and search by named query form.
     */
    @RequestMapping("*")
    public void catchAll(@ModelAttribute AddressModel address) {
    	System.err.println("-------------------");
    }
}
